
const request = require('request');
const url = 'http://dingxin.market.alicloudapi.com/dx/sendSms'
const headers = { 'Authorization': 'APPCODE 83e8d2b1b8304ceda220fb8a0e118858' }

const sendCodeSms = (mobile, code) => {
    return new Promise((resolve, reject) => {
        request.post({
            url,
            headers,
            form: {
                mobile,
                param: 'code:' + code,
                tpl_id: 'TP1711063'
            },
        }, (error, response, body) => {
            if(error){
                console.log('请求出错')
                reject({code: -1, msg: '服务器请求出错', data: error})
                return
            }
            
            if (response.statusCode == 200) {
                resolve(JSON.parse(body))
            } else {
                reject({code: 1, msg: '发送失败', data: response})
            }
        }
        )
    })
}

const sendSmsByTpl = (mobile, params, tpl_id) => {
    return new Promise((resolve, reject) => {
        let param = ''
        for(let prop in params){
            param += (prop + ':' + params[prop] + ',')
        }
        let form = {mobile, param, tpl_id}
        request.post({
            url,
            headers,
            form,
        }, (error, response, body) => {
            if(error){
                console.log('请求出错')
                reject({code: -1, msg: '服务器请求出错', data: error})
                return
            }
            
            if (response.statusCode == 200) {
                resolve(JSON.parse(body))
            } else {
                reject({code: 1, msg: '发送失败', data: response})
            }
        }
        )
    })
}

module.exports = {
    sendCodeSms, sendSmsByTpl
}